package lumis.portal.presentation.tag.page;

import java.util.List;

import lumis.portal.PortalException;
import lumis.portal.authentication.SessionConfig;
import lumis.portal.css.CssConfig;
import lumis.portal.css.ICssManager;
import lumis.portal.manager.ManagerFactory;
import lumis.portal.page.IPageManager;
import lumis.portal.page.PageConfig;
import lumis.portal.presentation.core.HTMLFragmentComponent;
import lumis.portal.presentation.core.LayoutFilePage;
import lumis.portal.transaction.PortalTransactionFactory;

import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.MarkupStream;
import org.apache.wicket.util.string.AppendingStringBuffer;

/**
 * Injects the page's links components. 
 * @version $Revision: 13093 $ $Date: 2011-05-28 18:40:18 -0300 (Sat, 28 May 2011) $
 * @since 6.0.0
 */
public class PageLinksComponent extends HTMLFragmentComponent 
{
	/**
	 * Serial version identifier.
	 * @since 6.0.0
	 */
	private static final long serialVersionUID = 1L;

	public PageLinksComponent(String id, boolean autoRenderBodyOnly) 
	{
		super(id, autoRenderBodyOnly);
	}

	@Override
	protected CharSequence getHTMLFragment(MarkupStream markupStream, ComponentTag openTag) 
	{
		try
		{
			AppendingStringBuffer pageLinks = new AppendingStringBuffer(500);
			
			LayoutFilePage page = ((LayoutFilePage)getPage());
			SessionConfig sessionConfig = SessionConfig.getCurrentSessionConfig();
			PageConfig pageConfig = page.getPageWebResource().getPage();

			// information to prevent db access every page view.
			if (pageConfig.getType() == PageConfig.PAGE_TYPE_USER)
			{
				IPageManager pageManager = ManagerFactory.getPageManager();
				List<String> cssIds = pageManager.getCssIdsRecursively(sessionConfig, pageConfig.getId(), PortalTransactionFactory.getCurrentTransaction());

				ICssManager cssManager = ManagerFactory.getCssManager();

				for (String cssId : cssIds)
				{
					CssConfig cssConfig = cssManager.get(sessionConfig, cssId, PortalTransactionFactory.getCurrentTransaction());
					String cssFilePath = cssConfig.getFilePath();

					if (cssFilePath != null)
						pageLinks.append(page.getPageDocType().formatW3CClosedTag("link type=\"text/css\" rel=\"stylesheet\" href=\"" + cssFilePath + "\""));
				}
			}
			else
			{
				pageLinks.append(page.getPageDocType().formatW3CClosedTag("link type=\"text/css\" rel=\"stylesheet\" href=\"lumis/portal/client/stylesheet/portal.css\" charset=\"UTF-8\" "));
			}
			return pageLinks;
		}
		catch (PortalException e)
		{
			throw new RuntimeException(e);
		}
	}
}
